<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    top="3%"
    width="63%"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
             label-width="80px"
             style="height:400px;overflow-y: auto;-ms-overflow-style: none;overflow: -moz-scrollbars-none;">
      <el-form-item label="类型" prop="sendRange">
        <!--        <el-input v-model="dataForm.range" placeholder="发送范围：0公告、1个人"></el-input>-->
        <el-radio-group v-model="dataForm.sendRange" @change="sendRangeType">
          <el-radio :label="0">公告</el-radio>
          <el-radio :label="1">个人</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="dataForm.title" placeholder="标题"></el-input>
      </el-form-item>
      <el-form-item label="通知类型" prop="noticeType">
        <!--        <el-input v-model="dataForm.type" placeholder="数据字典"></el-input>-->
        <el-select v-model="dataForm.noticeType" placeholder="请选择">
          <el-option
            v-for="i in noticeType"
            :key="i.id"
            :label="i.description"
            :value="i.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <!--        <el-input v-model="dataForm.content" placeholder="内容"></el-input>-->
        <mavon-editor :ishljs="true" :subfield="false" :toolbars="toolbars" v-model="dataForm.content" ref="md"
                      @imgAdd="$imgAdd"
                      @change="change"
                      :boxShadow="false"
                      style="min-height: 400px"/>
      </el-form-item>
      <el-form-item label="接收人" v-if="dataForm.sendRange === 1" prop="receivers">
        <!--        <el-input v-model="dataForm.receivers" placeholder="接收人，当range=1时启用"></el-input>-->

        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="dataForm.receivers" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="item in cities" :label="item.userId" :key="item.userId">{{item.username}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="danger" @click="dataFormSubmit(0)">保存草稿</el-button>
      <el-button type="primary" @click="dataFormSubmit(1)">发送通知</el-button>
    </span>
  </el-dialog>
</template>

<script>
  import {mavonEditor} from 'mavon-editor'
  import 'mavon-editor/dist/css/index.css'

  export default {
    components: {
      mavonEditor
    },
    data() {
      return {
        visible: false,
        html: '',
        configs: {},
        dataForm: {
          id: 0,
          title: '',
          sendRange: 0,
          noticeType: '',
          content: '',
          receivers: [],
          status: '',
          addUser: '',
          addTime: '',
          editUser: '',
          editTime: ''
        },
        dataRule: {
          title: [
            {required: true, message: '标题不能为空', trigger: 'blur'}
          ],
          sendRange: [
            {required: true, message: '发送范围：0公告、1个人不能为空', trigger: 'blur'}
          ],
          noticeType: [
            {required: true, message: '数据字典不能为空', trigger: 'blur'}
          ],
          content: [
            {required: true, message: '内容不能为空', trigger: 'blur'}
          ],
          // receivers: [
          //   {required: true, message: '接收人，当range=1时启用不能为空', trigger: 'blur'}
          // ],
          status: [
            {required: true, message: '状态：-2发送失败、-1删除、0新建未发送、1已发送不能为空', trigger: 'blur'}
          ],
          addUser: [
            {required: true, message: '添加人不能为空', trigger: 'blur'}
          ],
          addTime: [
            {required: true, message: '添加时间不能为空', trigger: 'blur'}
          ],
          editUser: [
            {required: true, message: '修改人不能为空', trigger: 'blur'}
          ],
          editTime: [
            {required: true, message: '修改时间不能为空', trigger: 'blur'}
          ]
        },
        // 通知类型列表
        noticeType: [],
        toolbars: {
          bold: true, // 粗体
          italic: true, // 斜体
          header: true, // 标题
          underline: true, // 下划线
          strikethrough: true, // 中划线
          mark: true, // 标记
          quote: true, // 引用
          ol: true, // 有序列表
          ul: true, // 无序列表
          link: true, // 链接
          imagelink: true, // 图片链接
          table: true, // 表格
          fullscreen: true, // 全屏编辑
          htmlcode: true, // 展示html源码
          help: true, // 帮助
          trash: true, // 清空
          /* 2.1.8 */
          alignleft: true, // 左对齐
          aligncenter: true, // 居中
          alignright: true, // 右对齐
          preview: true, // 预览
        },
        checkAll: false,
        checkedCities: [],
        cities: [],
        isIndeterminate: false
      }
    },
    created() {
      this.getSendRange()
    },
    methods: {
      init(id) {
        this.dataForm.id = id || 0
        this.visible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.id) {
            this.$http({
              url: this.$http.adornUrl(`/notice/imsglog/info/${this.dataForm.id}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.title = data.imsgLog.title
                this.dataForm.sendRange = data.imsgLog.sendRange
                this.dataForm.noticeType = data.imsgLog.noticeType
                this.dataForm.content = data.imsgLog.content
                this.dataForm.receivers = data.imsgLog.receivers
                this.dataForm.status = data.imsgLog.status
                this.dataForm.addUser = data.imsgLog.addUser
                this.dataForm.addTime = data.imsgLog.addTime
                this.dataForm.editUser = data.imsgLog.editUser
                this.dataForm.editTime = data.imsgLog.editTime
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit(status) {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            this.$http({
              url: this.$http.adornUrl(`/notice/imsglog/${!this.dataForm.id ? 'save' : 'update'}`),
              method: 'post',
              data: this.$http.adornData({
                'id': this.dataForm.id || undefined,
                'title': this.dataForm.title,
                'sendRange': this.dataForm.sendRange,
                'noticeType': this.dataForm.noticeType,
                'content': this.dataForm.content,
                'receivers': this.dataForm.receivers,
                'status': status,
                'addUser': this.dataForm.addUser,
                'addTime': this.dataForm.addTime,
                'editUser': this.dataForm.editUser,
                'editTime': this.dataForm.editTime
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      // 获取通知类型的范围
      getSendRange() {
        this.$http({
          url: this.$http.adornUrl(`/data/childrens/16`),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.noticeType = data.list
          } else {
            this.$message.error(data.msg)
          }
        })
      },
      // 将图片上传到服务器，返回地址替换到md中
      $imgAdd(pos, $file) {
        var formdata = new FormData();
        formdata.append('image', $file);
        axios({
          url: 'server url',
          method: 'post',
          data: formdata,
          headers: {'Content-Type': 'multipart/form-data'},
        }).then((url) => {
          // 第二步.将返回的url替换到文本原位置![...](0) -> ![...](url)
          /**
           * $vm 指为mavonEditor实例，可以通过如下两种方式获取
           * 1. 通过引入对象获取: `import {mavonEditor} from ...` 等方式引入后，`$vm`为`mavonEditor`
           * 2. 通过$refs获取: html声明ref : `<mavon-editor ref=md ></mavon-editor>，`$vm`为 `this.$refs.md`
           */
          $vm.$img2Url(pos, url);
        })
      },
      change(value, render) {
        // render 为 markdown 解析后的结果
        this.html = render;
      },
      submit() {
        console.log(this.dataForm.content);
        console.log(this.html);
        this.$message.success('提交成功！');
      },
       handleCheckAllChange(val) {
        var checkedCities = this.cities
        this.checkedCities = val ?checkedCities : [];
        this.isIndeterminate = false;
      },
      handleCheckedCitiesChange(value) {
        let checkedCount = value.length;
        this.checkAll = checkedCount === this.cities.length;
        this.isIndeterminate = checkedCount > 0 && checkedCount < this.cities.length;
        // this.cities = value;
      },
      sendRangeType(val) {
        if (val == 1) {
          this.$http({
            url: this.$http.adornUrl(`/sys/user/list`),
            method: 'get',
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.cities = data.page.list
              this.checkAll = false
              this.checkedCities = []
              this.isIndeterminate = false
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      }
    }
  }
</script>
